package net.kucoe.macarun;

import java.util.ArrayList;
import java.util.List;

/**
 * Process matching
 * 
 * @author Vitaliy Basyuk
 */
public class Match {
    private final Object matchingObject;
    private final List<Case> cases = new ArrayList<Case>();
    
    protected Match(final Object object) {
        matchingObject = object;
    }
    
    /**
     * Creates case pattern.
     * 
     * @param clazz
     * @return {@link Case}
     */
    public Case inCase(final Class<?> clazz) {
        Case caseO = new Case(clazz);
        if (caseO.is(matchingObject)) {
            cases.add(caseO);
        }
        return caseO;
    }
    
    /**
     * Creates default pattern.
     * 
     * @return {@link Case}
     */
    public Case inDefault() {
        return inCase(Object.class);
    }
    
    /**
     * Executes matching and returns result for case {@link Run}.
     * 
     * @return result
     */
    @SuppressWarnings("unchecked")
    public <T> T run() {
        Object result = null;
        for (Case case0 : cases) {
            if (case0.isTrue(matchingObject)) {
                result = case0.run(matchingObject);
                if (case0.isBreaking()) {
                    break;
                }
            }
        }
        return (T) result;
    }
    
}
